package net.chathu.airgw.model.conn 
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	import flash.system.Security;
	import net.chathu.airgw.Config;
	import net.chathu.airgw.Debug;
	import net.chathu.airgw.Soul;
	import net.chathu.airgw.SoulManager;
	/**
	 * ...
	 * @author ze
	 */
	public class IRCConnectionListener 
	{
		
		public static var _serverSocket:ServerSocket;

		public function IRCConnectionListener(localPort:int, localAddress:String="0.0.0.0") 
		{
			//Debug.echo("Sandbox type: " + Security.sandboxType);
			try {
				_serverSocket = new ServerSocket();
				_serverSocket.addEventListener(Event.CONNECT, onConnect);
				_serverSocket.addEventListener(Event.CLOSE, onClose);
				_serverSocket.bind(localPort, localAddress); // Pass in the port number you want to listen on
				
				Debug.echo("Listening on: " + localAddress + ":" + localPort);
			} catch (err:Error) {
				Debug.echo("Error during IRCConnectionListener init: " + err.message);
				Debug.echo("Maybe this port (" + localPort + ") is in use! Please check it, then restart the application!");
				throw err;
			}
			Debug.echo("Connect with your IRC client to port: " + _serverSocket.localPort);
		}
		
		
		public function start():void
		{
			trace("Start listening...");
			_serverSocket.listen();
		}
		
		
		public function stop():void
		{
			trace("Stop listening...");
			_serverSocket.close();
			
		}
		
		public function destroy():void
		{
			trace("Destroy...");
			stop();
			_serverSocket.removeEventListener(Event.CONNECT, onConnect);
			_serverSocket.removeEventListener(Event.CLOSE, onClose);
			_serverSocket = null;
		}
		
		private function onConnect(e:ServerSocketConnectEvent):void
		{
			trace("IRC client connected");
			var socket:Socket = e.socket;
			var soul:Soul = SoulManager.createSoul();
			soul.ircConnection = new IRCConnection(socket, soul);
		}
		
		private function onClose(e:Event):void
		{
			//............nooo!
			//var socket:Socket = Socket(e.target);
			//destroy soul
			trace("Listening stopped");
			
			
		}
		
		public function get port():int {
			if (_serverSocket)
			{
				return _serverSocket.localPort;	
			} else {
				return -1;
			}
			
		}
		
		
	}

}